#include <iostream>
#include <memory>
/*

shared_ptr
改变资源的引用计数

weak_ptr
不改变资源的引用计数, 没有提供operator*()和operator->()函数
*/

/*
以下代码演示循环引用导致内存泄漏问题！！！
*/
#if 0
class B;
class A {
public:
    A() {
        std::cout << "A()" << std::endl;
    }
    ~A() {
        std::cout << "~A()" << std::endl;
    }

    std::shared_ptr<B> pB;
};

class B {
public:
    B() {
        std::cout << "B()" << std::endl;
    }
    ~B() {
        std::cout << "~B()" << std::endl;
    }
    std::shared_ptr<A> pA;
};

int main() {
    std::shared_ptr<A> pa(new A());
    std::shared_ptr<B> pb(new B());
    pa->pB = pb;  // B对象的引用计数变为2
    pb->pA = pa;  // A对象的引用计数也变为2
}  // A和B都不会释放，导致内存泄漏
#endif

class A;
class B {
public:
    B() {
        std::cout << "B()" << std::endl;
    }
    ~B() {
        std::cout << "~B()" << std::endl;
    }
    void test() {
        std::cout << "do something" << std::endl;
    }
    std::shared_ptr<A> pA;
};
class A {
public:
    A() {
        std::cout << "A()" << std::endl;
    }
    ~A() {
        std::cout << "~A()" << std::endl;
    }

    void func() {
        std::shared_ptr<B> pB_ = pB.lock();
        if (pB_) {
            pB_->test();
        }
    }
    std::weak_ptr<B> pB;
};

int main() {
    std::shared_ptr<A> pa(new A());
    std::shared_ptr<B> pb(new B());
    pa->pB = pb;  // B对象的引用计数仍然是1
    pb->pA = pa;  // A对象的引用计数变为2
    pa->func();
    pb->test();
}
